package acom.dhy.qigsaw2test

import android.os.IBinder
import android.view.WindowManager
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Root
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith


@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @JvmField
    @Rule
    val activityScenarioRule = ActivityScenarioRule(MainActivity::class.java)

    @Before
    fun before() {
        Intents.init()
    }

    @After
    fun after() {
        Intents.release()
    }

    @Test
    fun fetchSplitInfo() {
        onView(withId(R.id.btUpdateSplitInfo)).perform(click())

//        Thread.sleep(1000)
        onView(withText("OK"))
            .inRoot(isToast())
            .check(matches(isDisplayed()))
    }

    @Test
    fun installJava() {
        onView(withId(R.id.btJava)).perform(click())
        intended(hasComponent("com.iqiyi.qigsaw.sample.java.JavaSampleActivity"))
        onView(withResourceName("tvJavaMsg")).check(matches(isDisplayed()))
    }

    @Test
    fun installAssets() {
        onView(withId(R.id.btAssets)).perform(click())
        onView(withText("Asset Content")).check(matches(isDisplayed()))
    }

    @Test
    fun installNative() {
        onView(withId(R.id.btNative)).perform(click())
        intended(hasComponent("com.iqiyi.qigsaw.sample.ccode.NativeSampleActivity"))
    }

    private fun isToast(): Matcher<Root> {
        return ToastMatcher()
    }

    class ToastMatcher : TypeSafeMatcher<Root>() {
        override fun describeTo(description: Description) {
            description.appendText("is toast")
        }

        override fun matchesSafely(root: Root): Boolean {
            val type: Int = root.windowLayoutParams.get().type
            if (type == WindowManager.LayoutParams.TYPE_TOAST) {
                val windowToken: IBinder = root.decorView.windowToken
                val appToken: IBinder = root.decorView.applicationWindowToken
                if (windowToken === appToken) {
                    //means this window isn't contained by any other windows.
                    return true
                }
            }
            return false
        }
    }
}